package com.apes.fn.server.vehicleFile.server;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.vehicleFile.model.VehicleFileArea;
import com.apes.fn.server.vehicleFile.model.VehicleFileAreaEnum;
import com.apes.fn.server.vehicleFile.repository.VehicleFileAreaRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-11-02 14:13
 **/
@Service("vehicleFileAreaServer")
public class VehicleFileAreaServer extends DomainService {
    @Autowired
    private VehicleFileAreaRepository vehicleFileAreaRepository;

    private VehicleFileArea save(SimpleRequest request){
        VehicleFileArea vehicleFileArea = request.getO(VehicleFileArea.class);
        return vehicleFileAreaRepository.saveAndFlush(vehicleFileArea);
    }
    private VehicleFileArea update(SimpleRequest request){
        VehicleFileArea vehicleFileArea = request.getO(VehicleFileArea.class);
        return vehicleFileAreaRepository.saveAndFlush(vehicleFileArea);
    }

    private VehicleFileArea delete(SimpleRequest request){
        VehicleFileArea vehicleFileArea = request.getO(VehicleFileArea.class);
        vehicleFileArea.setDeleted(true);
        return vehicleFileAreaRepository.saveAndFlush(vehicleFileArea);
    }

    private Object searchUploadApi(SimpleRequest request){

        List<String> collect = Arrays.stream(VehicleFileAreaEnum.values()).map(VehicleFileAreaEnum::getName).collect(Collectors.toList());

        return pageInfo(request.getJO(),collect);
    }

    /**
     * 手动分页
     * @param jo
     * @param list
     * @return
     */
    public PageImpl pageInfo(JSONObject jo, List list){
        int size = (Integer) jo.get("page")*(Integer) jo.get("size");
        List result = new ArrayList<>();
        for (int i = size+1; i <= size+(Integer) jo.get("size"); i++) {
            if (list.size()>=i)result.add(list.get(i-1));
        }
        Pageable pageable = PageRequest.of(((Integer) jo.get("page")), (Integer) jo.get("size"));
        PageImpl page = new PageImpl(result, pageable, list.size());
        return page;
    }
}
